package com.design.reactor.stretchIO._1_singleReactorSingleThread.impl.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

public class ReaderHandler extends AbstractHandler {

    static final int MAX_IN = 1024;
    static ByteBuffer input = ByteBuffer.allocate(MAX_IN);
    public ReaderHandler()  {
    }
    public ReaderHandler(Selector selector, SocketChannel socketChannel) throws IOException {
        socketChannel.configureBlocking(false);
        // 也可以注解注册SelectionKey.OP_READ; 这里先不关心任何事件， 后面注册读事件
        SelectionKey selectionKey = socketChannel.register(selector, 0);//注册一个不存在的事件
        selectionKey.attach(this);
        selectionKey.interestOps(SelectionKey.OP_READ);//将此键的 interest 集合设置为给定值 ： 注册读事件
        selector.wakeup();//唤醒前一个阻塞的socket
    }


    @Override
    public void handle(Selector selector, SelectableChannel channel, SelectionKey selectionKey)  {
        try{
            SocketChannel socketChannel = (SocketChannel) channel;
            input.clear();
            //读入
            socketChannel.read(input);
            input.flip();
            // 写出到String
            String msg = String.valueOf( Charset.forName("UTF-8").decode(input).array() );
            System.out.println("--- ReaderHandler.handle() 处理 msg : " + msg);
            // 处理数据
            process(socketChannel);
//            if(socketChannel!=null) {
//                new WriterHandler(selector,socketChannel);
//            }
        }catch (Exception e){
            selectionKey.cancel();
        }
    }
    boolean inputIsComplete() {
        // 加入实现
        return true;
    }

    void process(SocketChannel socketChannel) throws IOException {
        input.clear();
        input.put(("--- ReaderHandler 服务端接收到消息，正在处理中......").getBytes());
        socketChannel.write(input);
    }
}
